package com.lagou.server;


import com.lagou.server.classload.WebClassLoader;
import com.lagou.server.pojo.Context;
import com.lagou.server.pojo.Host;
import com.lagou.server.pojo.Mapper;
import com.lagou.server.pojo.Server;
import com.lagou.server.pojo.Wrapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Minicat的主类
 */

public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private Server server = new Server();

    private List<Mapper> serviceList = new ArrayList<>();

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */

        //加载server.xml读取配置server配置信息
        loadParseServlet();


        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/


        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while (true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, server);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }


    }

    private void loadParseServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            Element serverElement = (Element) rootElement.selectSingleNode("//service");
            List<Element> serviceNodes = serverElement.selectNodes("//service");
            //存储Host
            Map<String, Host> hostMap = new HashMap<>();

            //遍历service
            for (Element serviceElement : serviceNodes) {
                Element engineNode = (Element) serviceElement.selectSingleNode("//Engine");
                List<Element> hosts = engineNode.selectNodes("//Host");
                //存储项目
                Map<String, Context> contextMap = new HashMap<>();
                for (Element hostElement : hosts) {
                    String name = hostElement.attributeValue("name");
                    String appBase = hostElement.attributeValue("appBase");
                    File file = new File(appBase);
                    if (!file.exists() || file.list() == null) {
                        break;
                    }
                    String[] list = file.list();
                    for (String path : list) {
                        contextMap.put(path, loadContextServlet(appBase, path));
                        hostMap.put(name + ":" + port, new Host(contextMap));
                    }
                }
                serviceList.add(new Mapper(hostMap));
            }
            server.setMapperList(serviceList);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //解析项目里配置的web.xml
    private Context loadContextServlet(String appBase, String contextName) throws FileNotFoundException, DocumentException, InstantiationException, IllegalAccessException {
        Context context = new Context();
        String webPath = appBase + "/" + contextName;
        File file = new File(webPath);
        if (!file.exists()) {
            System.out.println("not found " + webPath);
            return null;
        }
        List<Wrapper> wrappers = loadServlet(appBase, contextName);
        return new Context(contextName, wrappers);
    }

    private List<Wrapper> loadServlet(String appBase, String contextName) throws FileNotFoundException, DocumentException, IllegalAccessException, InstantiationException {
        String webPath = appBase + "/" + contextName + "/web.xml";
        FileInputStream fileInputStream = new FileInputStream(webPath);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(fileInputStream);
        Element rootElement = document.getRootElement();
        List<Element> servletElements = rootElement.selectNodes("//servlet");
        List<Wrapper> list = new ArrayList<>();
        for (Element serverElement : servletElements) {
            Element servletElement = (Element) serverElement.selectSingleNode("//servlet-name");
            Element servletClassElement = (Element) serverElement.selectSingleNode("//servlet-class");
            String servletClass = servletClassElement.getStringValue();
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletElement.getStringValue() + "']");
            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

            // 1. 初始化自定义的类加载器
            WebClassLoader myClassLoader = new WebClassLoader();
            Class<?> aClass = myClassLoader.findClass(appBase + "/" + contextName, servletClass);
            Wrapper wrapper = new Wrapper(urlPattern, (HttpServlet) aClass.newInstance());
            list.add(wrapper);
        }
        return list;
    }


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();


    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
